package com.joker.aigc.chat.service.event.listener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joker.aigc.domain.entity.UserApply;
import com.joker.aigc.chat.domain.entity.websocket.WebSocketBaseVo;
import com.joker.aigc.chat.domain.entity.websocket.WebSocketFriendApplyVo;
import com.joker.aigc.domain.enums.UserApplyStatusEnum;
import com.joker.aigc.mapper.UserApplyMapper;
import com.joker.aigc.chat.service.PushService;
import com.joker.aigc.chat.service.adapter.WebSocketAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
import com.joker.aigc.chat.service.event.UserApplyEvent;

/**
 * 好友申请监听器
 *
 * @author zhongzb create on 2022/08/26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserApplyListener {


    private final UserApplyMapper userApplyMapper;

    private final PushService pushService;

    /**
     * 通知好友申请的后续工作
     *
     * @param event 监听时间传递过来的数据。
     */
    @Async
    @TransactionalEventListener(classes = UserApplyEvent.class, fallbackExecution = true)
    public void notifyFriend(UserApplyEvent event) {

        UserApply userApply = event.getUserApply();
        // 保存用户信息
        userApplyMapper.insert(userApply);
        // 开始发送消息
        WebSocketFriendApplyVo vo = new WebSocketFriendApplyVo();

        // 设置未处理消息
        Long count = userApplyMapper.selectCount(new LambdaQueryWrapper<UserApply>()
                .eq(UserApply::getApplyUid, userApply.getToUid())
                .eq(UserApply::getStatus, UserApplyStatusEnum.APPLY));

        vo.setUnreadCount(count);
        vo.setUid(userApply.getApplyUid());


        // 构建消息
        WebSocketBaseVo<WebSocketFriendApplyVo> webSocketFriendApplyVoWebSocketBaseVo = WebSocketAdapter.buildApplySend(vo);
        log.info("好友申请 开始发送消息->{}", webSocketFriendApplyVoWebSocketBaseVo);
        // 开始推送消息
        pushService.sendWebSocket(webSocketFriendApplyVoWebSocketBaseVo, userApply.getToUid());

    }

}
